package com.itheima.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class MyUerDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        QueryWrapper<com.itheima.pojo.User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_name",username);
        com.itheima.pojo.User mysqluser = userMapper.selectOne(queryWrapper);
        Collection<GrantedAuthority> autorities = new ArrayList<>();
        List<String> list = userMapper.selectRoles(username);
        if(list != null && list.size()>0){
            for(String role : list){
                autorities.add(new SimpleGrantedAuthority(role));
            }
        }
        if(mysqluser == null)return null;
        User user = new User(mysqluser.getUserName(),mysqluser.getPassword(),autorities);
        return user;
    }
}
